package de.fuberlin.dbs.wm.service;

import java.sql.SQLException;
import java.util.List;

import de.fuberlin.dbs.wm.dao.Dao;
import de.fuberlin.dbs.wm.dao.GoalDao;
import de.fuberlin.dbs.wm.dao.MatchDao;
import de.fuberlin.dbs.wm.dao.PlayerDao;
import de.fuberlin.dbs.wm.dao.UseDao;
import de.fuberlin.dbs.wm.dao.model.Goal;
import de.fuberlin.dbs.wm.dao.model.Match;
import de.fuberlin.dbs.wm.dao.model.Player;
import de.fuberlin.dbs.wm.dao.model.Team;
import de.fuberlin.dbs.wm.dao.model.Use;
import de.fuberlin.dbs.wm.util.NotAllowedException;

public class MatchService {
	
	public static void insertPlayerToMatch(Use use) throws Exception {
		Match match;
		Player player;
		PlayerService playerService = new PlayerService();
		// check if match and player exists
		try {
			match = MatchDao.getMatchById(use.getMatchId());
			player = PlayerDao.getPlayerById(use.getPlayerId());
		}
		catch (SQLException e) {
			throw new Exception("Error: Match and/or Player doesn't exist! " + e.getMessage());
		}
		// check if player plays in one of the teams
		Team team = playerService.getTeamOfPlayer(player.getId());
		if(team == null) throw new Exception("Error retrieving team data!");
		if(!(match.getTeamOneName().equals(team.getName()) || match.getTeamTwoName().equals(team.getName())))
			throw new Exception("Error: Player is not in one of the teams!");
		//TODO everything checked? what is checked by databse constraints and what should be checked by the service?
		// write to database
		try {
			UseDao.insertUse(use);
		}
		catch (SQLException e) {
			throw new Exception("Error inserting use to database: " + e.getMessage());
		}
	}
	
	public static void insertGoal(Goal goal) throws NotAllowedException, Exception{
		if(Dao.hasMatchWriteAccess(goal.getMatchId())) {
			List<Use> useList = PlayerDao.getUsesByID(goal.getPlayerId());
			boolean found = false;
			for(Use u : useList) if(u.getMatchId() == goal.getMatchId()) found = true;
			if(!found) throw new Exception("Error: Player hasn't played this match");
			// write to database
			try { GoalDao.insertGoal(goal); }
			catch (SQLException e) { throw new Exception("Error writing goal to database: " + e.getMessage()); }
		}
		else throw new NotAllowedException();
	}
}
